import { Directive, DirectiveBinding } from "vue";

interface PreventReClickBinding extends DirectiveBinding {
  value: (...args: any[]) => void;
  arg?: string;
}
interface ThrottleElement extends HTMLElement {
  _clickHandler?: (...args: any[]) => void;
}
const preventReClick: Directive = {
  mounted(el: ThrottleElement, binding: PreventReClickBinding) {
    const { value, arg } = binding;
    let delay = 1000;

    if (arg) {
      delay = parseInt(arg);
      if (isNaN(delay)) {
        delay = 1000;
      }
    }

    if (typeof value !== "function") {
      throw new Error("v-prevent-re-click directive value must be a function");
    }

    let canClick = true;
    const clickHandler = (...args: any[]) => {
      if (canClick) {
        canClick = false;
        value(...args);
        setTimeout(() => {
          canClick = true;
        }, delay);
      }
    };

    el._clickHandler = clickHandler;
    el.addEventListener("click", clickHandler);
  },
  beforeUnmount(el: HTMLElement & { _clickHandler?: (...args: any[]) => void }) {
    if (el._clickHandler) {
      el.removeEventListener("click", el._clickHandler);
    }
  },
};

export default preventReClick;
